const cp = require('child_process');
const fs = require('fs');
var path = require('path');

//var root = "gcc base/";
var root = "gcc/";


var pause = () => {
  const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  readline.question(`pause`, name => {
    readline.close();
  });
};

var build = async (path, hardFloat, cpp, p) => {
  return new Promise((resolve, reject) => {
    var child;
    var param = ["-O2", "-Os", "-quiet", "-Wno-write-strings", "-Wno-attributes", "-Wno-builtin-declaration-mismatch", "-fno-builtin",
      "-G0",
      "-fno-unwind-tables",
      "-fno-asynchronous-unwind-tables",
      "-fno-pic",

      "-fno-exceptions",
      "-fno-trapv",
      "-fno-stack-protector",
      "-fno-delete-null-pointer-checks",
      "-fno-builtin-trap",
      "-fno-tree-dce",
      "-fno-tree-ccp"
    ];
    if (hardFloat) {
      param = [...param, "-mcustom-fadds=0", "-mcustom-fsubs=1", "-mcustom-fmuls=2", "-mcustom-fdivs=3", "-mcustom-fcmpeqs=8", "-mcustom-fcmpges=9", "-mcustom-fcmpgts=10", "-mcustom-fcmples=11", "-mcustom-fcmplts=12", "-mcustom-fcmpnes=13", "-mcustom-fixsi=14"];
    }
    param = [...param, ...p];

    var file = path.split("/");
    file = file[file.length - 1];
    var out = "build/" + file + ".s";
    param = [...param, path + (cpp ? ".cpp" : ".c"), "-o", out];

    if (cpp) {
      child = cp.spawn(root + "cc1plus.exe", param, {
        //cwd: job.path
      });
    } else {
      child = cp.spawn(root + "cc1.exe", param, {
        //cwd: job.path
      });
    }

    var stdin = "";
    var stdout = "";
    var stderr = "";

    child.stdin.on('data', (data) => {
      stdin += data;
    });
    child.stdout.on('data', (data) => {
      stdout += data;
    });
    child.stderr.on('data', (data) => {
      stderr += data;
    });
    child.on('close', (code) => {
      if (true || code != 0) {
        console.log(`${file} ${stdout} ${stderr} ${stdin}`);
        //setTimeout(() => { process.exit(1); }, 100);
      }
      resolve(out);
    });
  });
};

var read = async (filename) => {
  return new Promise((resolve, reject) => {
    fs.readFile(filename, function (err, content) {
      resolve(content);
    });
  });
};

var concat = async (files, target) => {
  var content = "";
  for (var i = 0; i < files.length; i++) {
    content += await read(files[i]);
  }

  fs.writeFileSync(target, content);
};

module.exports = { build, pause, concat };
